package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String avatar, String nickname) {
        if (StringUtils.isEmpty(avatar)) { // 如果是空的就走后台登录的逻辑
            boolean captchaEnabled = configService.selectCaptchaEnabled();
            // 验证码开关
            if (captchaEnabled) {
                validateCaptcha(username, code, uuid);
            }
            // 用户验证
            Authentication authentication = null;
            try {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                AuthenticationContextHolder.setContext(authenticationToken);
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(authenticationToken);
            } catch (Exception e) {
                if (e instanceof BadCredentialsException) {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                    throw new UserPasswordNotMatchException();
                } else {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                    throw new ServiceException(e.getMessage());
                }
            } finally {
                AuthenticationContextHolder.clearContext();
            }
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            loginUser.setAvatar(avatar); // 微信用户唯一标识
            recordLoginInfo(loginUser.getUserId());
            return tokenService.createToken(loginUser);

        } else {
            // 微信登录
            SysUser user = userMapper.selectUserByOpenId(avatar);
            if (user == null) {
                user = new SysUser();
                user.setOpenId(avatar); // 根据头像的地址设置为微信的openID
//              TODO   user.setRoleId();
                user.setUserName(UUID.randomUUID().toString().replace("-", "").substring(0, 10) +
                        ThreadLocalRandom.current().nextInt(10));
                user.setNickName(nickname);
                userMapper.insertUser(user);
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setUser(user);
            BeanUtils.copyProperties(user, loginUser);
            loginUser.setAvatar(avatar);
            return tokenService.createToken(loginUser);

        }
        // 生成token 将生成的token信息，存放到jwt的Claims
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public static void main(String[] args) {

        String str = "https://thirdwx.qlogo.cn/mmopen/vi_32/1ZHhicDkgFtIalpjPJibUSewGl91d1RX0yWRaQPeDWHiaZLWyJB3iaJh5jIF8Viaq9picibrbO3hTV0VXRPlc7VibhfzoA/132";
        String str1 = "https://thirdwx.qlogo.cn/mmopen/vi_32/1ZHhicDkgFtIalpjPJibUSewGl91d1RX0yWRaQPeDWHiaZLWyJB3iaJh5jIF8Viaq9picibrbO3hTV0VXRPlc7VibhfzoA/132";
        System.out.println("str.equals(str1) = " + str.equals(str1));
    }
}
